			package com.wny;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.teamconnections.wny.R;

import android.R.id;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.text.AndroidCharacter;
import android.util.EventLogTags.Description;
import android.view.*;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

// TODO: Auto-generated Javadoc
/**
 * The Class WNYMainActivity.
 */
public class WNYMainActivity extends ListActivity implements LocationListener {

	//NetworkHandler communicate;

	/** The radius. */
	double radius = .01;

	/** The my comm. */
	SocketsClient myComm;

	/** The lists. */
	LocalListStorage theLists;

	/** The m inflater. */
	LayoutInflater mInflater;

	/** The my location. */
	Location myLocation;

	/** The my provider. */
	LocationManager myProvider;

	/** The uid. */
	int uid = -1;

	/** The friend_uid. */
	int friend_uid;

	/** The is_friend. */
	boolean is_friend = false;

	/** The save_username. */
	String save_username=null;

	/** The save_password. */
	String save_password=null;
	
	int event_id;

	/**
	 * Called when the activity is first created.
	 *
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		theLists = new LocalListStorage();
		setContentView(R.layout.main);
		myProvider = (LocationManager) getSystemService(LOCATION_SERVICE);
		mInflater =(LayoutInflater) getSystemService(
				Activity.LAYOUT_INFLATER_SERVICE);
		myLocation = null;
	}

	/**
	 * Switch view to create.
	 *
	 * @param View v
	 */
	public void switchViewToCreate(View v)
	{
		setContentView(R.layout.newaccountview);

	}

	/**
	 * Switch to login.
	 *
	 * @param View v
	 */
	public void switchToLogin(View v)
	{

		setContentView(R.layout.loginscreen);
	}

	/**
	 * Update location.
	 *
	 * @param View v
	 */
	private void updateLocation(View V)
	{

	}

	/**
	 * Try login.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void tryLogin(View V) throws IOException

	{
		//The Username and password for user
		String username = ((EditText)findViewById(R.id.login_username)).getText().toString();
		String password = ((EditText)findViewById(R.id.login_password)).getText().toString();

		char[] t;
		//initializes the SQL query to log in a user
		StringBuilder toSend = new StringBuilder("other=log&name=");
		//Sees if remember me box is selected, if it is, remember them and autofill the username and password slots
		if( ((CheckBox)findViewById(R.id.checkRememberMe)).isChecked()) {

			if( (save_username==null) || (username!=save_username && username.length()!=0) ){

				saveLoginInfo(username, password);
			}
			//autofills user credentials
			FillinCredientals(V);
			//send remember me credentials to server
			t = myComm.sendData((toSend + save_username + "&pwd="+ save_password + "\n").getBytes());
		}

		else{
			//otherwise remember me is not checked. Just send the current username and password to server
			t = myComm.sendData((toSend + username + "&pwd="+ password + "\n").getBytes());
		}
		//if first bit is 1, query is successful. User is admitted into the program
		if (t[0]=='1')
		{
			//switch to authenticated view and get the UID for user
			setContentView(R.layout.loggedinview);
			setUID(username);
			displayWithToast("Sucessfuly logged in", 4000);
		}
		else
		{
			displayWithToast("Invalid login.", 4000);
		}

	}

	/**
	 * Fill in credientals.
	 *
	 * @param View v
	 */
	public void FillinCredientals (View V){

		//checks to see parameters are not null. It then fills in the username ans password
		if(save_username!=null || save_password!=null){
			//fill in the username and password automatically when checked
			EditText username=((EditText)findViewById(R.id.login_username));
			username.setText(save_username);
			EditText password=((EditText)findViewById(R.id.login_password));
			password.setText(save_password);
		}
	}

	/**
	 * Sets the UID.
	 *
	 * @param username 
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	private void setUID(String username) throws IOException
	{
		char[] uid = myComm.sendData(("getid=user&name=" + username +"\n").getBytes());
		this.uid = Integer.valueOf(String.valueOf(uid).split("/")[0]);
	}

	/**
	 * Go to logged in view.
	 *
	 * @param View v
	 */
	public void goToLoggedInView(View V)
	//clears UI userlist before loading the logged in view
	{
		theLists.clear();
		populateList(theLists.getUserList());
		setContentView(R.layout.loggedinview);
	}

	/**
	 * Switch to user list.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	
	public void switchToUserList(View V) throws IOException
	{
		//populate the user list-get user info from server
		char[] listOfUsers = myComm.sendData("get=user\n".getBytes());
		theLists.setUserList(listOfUsers);
		setContentView(R.layout.thelistdisplay);
		populateList(theLists.getUserList());
	}

	/**
	 * Switch to friends list.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void switchToFriendsList(View V) throws IOException
	{
		//populates list with other users that are friends with the current user
		char[] listOfUsers = myComm.sendData(("get=friend&name="+String.valueOf(uid)+"\n").getBytes());

		displayUsers(listOfUsers);
	}

	/**
	 * Switch to events list.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void switchToEventsList(View V) throws IOException
	{
		//populates list with user Events
		char[] listOfEvents = myComm.sendData(("get=eventList&uid="+String.valueOf(uid)+"\n").getBytes());
		displayEvents(listOfEvents);
	}

	/**
	 * Switch to unfiltered events.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void switchToUnfilteredEvents(View V) throws IOException
	{
		//shows all events
		char[] listOfEvents = myComm.sendData(("get=event\n").getBytes());
		displayEvents(listOfEvents);
	}

	/**
	 * Gets the nearby users.
	 *
	 * @param View v
	 
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	//Uses Location Android class to call its GPS feature
	public void getNearbyUsers(View V) throws IOException
	{
		StringBuilder toSend = new StringBuilder("get=user&location=");
		double latitude;
		double longitude;
		if(myLocation==null)
		{
			latitude = 0;
			longitude = 0;
		}
		//if not null,get coordinates
		else
		{
			latitude = myLocation.getLatitude();
			longitude = myLocation.getLongitude();
		}
		//uses '#' as a delimeter
		toSend.append(latitude);
		toSend.append("#");
		toSend.append(longitude);
		toSend.append("#");
		toSend.append(radius);
		toSend.append("\n");
		char[] listOfUsers = myComm.sendData(toSend.toString().getBytes());
		//show users near you
		displayUsers(listOfUsers);
	}

	/**
	 * Display users.
	 *
	 * @param listOfUsers the list of users
	 */
	//show list of all users
	public void displayUsers(char[] listOfUsers)
	{
		theLists.setUserList(listOfUsers);
		setContentView(R.layout.thelistdisplay);
		populateList(theLists.getUserList());
	}

	/**
	 * Display events.
	 *
	 * @param listOfEvents the list of events
	 */
	public void displayEvents(char[] listOfEvents)
	{
		theLists.setEventList(listOfEvents);
		setContentView(R.layout.thelistdisplay);
		populateList(theLists.getEventList());
	}

	/**
	 * Change privacy level.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void changePrivacyLevel(View v) throws IOException
	{
		char[] newVal = myComm.sendData(("update=privacy&uid="+uid+"\n").getBytes());
		displayWithToast("Your profile is now " +String.valueOf(newVal).split("/")[0], 4000);

	}

	/**
	 * Display with toast.
	 *
	 * @param toShow the to show
	 * @param duration the duration
	 */
	//a wrapper function for the Toast class. Used to show messages onscreen
	private void displayWithToast(String toShow, int duration)
	{
		Toast temp = Toast.makeText(this, toShow, duration);
		temp.setGravity(Gravity.CENTER, 0, 0);
		temp.show();
	}

	/**
	 * Save login info.
	 *
	 * @param username the username
	 * @param password the password
	 */
	//saves remember me credentials  
	private void saveLoginInfo(String username, String password) {
		save_username=username;
		save_password=password;
	}

	/**
	 * To unauthenticated screen.
	 *
	 * @param View v
	 */
	//loads main menu
	public void toUnauthenticatedScreen(View V)
	{
		setContentView(R.layout.main);
	}

	/**
	 * Switch to create event.
	 *
	 * @param View v
	 */
	public void switchToCreateEvent(View V){
		setContentView(R.layout.create_event);
	}


	/**
	 * Try submit event.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void trySubmitEvent(View V) throws IOException{
		String eventName;
		String eventLocation;
		String description;
		StringBuffer toSend;
		int day;
		int month;
		int year;
		int Hour;
		int Minute;

		//pulls the event name, location, and description and sends it to the server
		eventName =     ((EditText)findViewById(R.id.eventname)).getText().toString();
		eventLocation = ((EditText)findViewById(R.id.eventlocation)).getText().toString();
		description = ((EditText)findViewById(R.id.editText3)).getText().toString();


		//uses date picker class to get event information
		DatePicker dp=(DatePicker)findViewById(R.id.datePicker);
		day=dp.getDayOfMonth();
		month=dp.getMonth()+1;
		year=dp.getYear();

		//time picker used to get hour and minute 
		TimePicker tp=(TimePicker)findViewById(R.id.timePicker);

		Hour=tp.getCurrentHour();
		
		Minute=tp.getCurrentMinute();
		
		toSend = new StringBuffer("add=event&title="+eventName+"&date="+year+"-"+month+"-"+day+" "+Hour+":"+Minute+":00"+"&description="+description+"&latitude=0&longitude=0"+"&organizerID="+uid+"\n");
		
		//checks to see if information sent to the server
		char[] result = myComm.sendData(toSend.toString().getBytes());
		
		
		
		
		if(result[0]=='0')
			displayWithToast("Problem making event):", 4000);
		else if(result[0]=='1')
		{
			displayWithToast("Sucessfuly added event (:", 4000);
			char[] get_eid=myComm.sendData( ("get=event&title="+eventName).getBytes());
			String the_result=String.valueOf(get_eid);
			fireLongToast(the_result,4000);
			setContentView(R.layout.loggedinview);
		}

	}

	/**
	 * Checks if user is friend.
	 *
	 * @param user_id the user_id
	 * @return true, if is user friend
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	
	public boolean isUserFriend(int user_id) throws IOException {

		char [] get_friend_info;
		String friend_info;
		
		get_friend_info=myComm.sendData(("get=friend&uid1="+uid +"&uid2="+friend_uid+"\n").getBytes());

		friend_info=String.valueOf(get_friend_info);	

		//if the UID is returned, it means the users are friends
		if( (String.valueOf(friend_info.charAt(0)).equals(String.valueOf(uid))) ){
			return true;
		}
		//otherwise return false
		return false;

	}


	/**
	 * Try to create account.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	
	public void tryCreateAccount(View V) throws IOException
	{
		String username =          ((EditText)findViewById(R.id.usernameBox)).getText().toString();
		String password =          ((EditText)findViewById(R.id.passwordBox)).getText().toString();
		String confirm_password =  ((EditText)findViewById(R.id.passwordConfirmBox)).getText().toString();
		String displayName =       ((EditText)findViewById(R.id.textName)).getText().toString();
		String email = null;
		String sex = null;

		boolean password_match;
		password_match= Password_Match_Check(password,confirm_password);
		//if passwords to not match let user know and return (exit function)
		if ( password_match==false){
			return;
		}
		//If skip email is checked, do not get email from textbox
		if(!((CheckBox)findViewById(R.id.emailCheckbox)).isChecked())
		{
			email = ((EditText)findViewById(R.id.emailBox)).getText().toString();
			//    	communicate.send(null);
		}
		//get user's sex
		if(((RadioButton)findViewById(R.id.radio0)).isChecked())
			sex="m";
		else
			sex="f";

		
		StringBuilder toSend = new StringBuilder("add=user&name=").append(username).append("&pwd=").append(password).
				append("&email=").append(email).append("&sex="+sex+"\n");
		try{
			//if 1, then data retrieved successfully. Else there was a problem making the account
			char[] v = myComm.sendData(toSend.toString().getBytes());
			if(v[0]=='1')
			{

				toSend = new StringBuilder("add=privacy&uid="+uid+"&private=1\n");
				myComm.sendData(toSend.toString().getBytes());
				setContentView(R.layout.loggedinview);
				setUID(username);
				displayWithToast("Sucessfully logged in", 4000);
			}

			else
			{
				displayWithToast("Problem creating account ):" , 4000);
			}

		}
		catch(Exception e)
		{
			displayWithToast("Error in network communication; action aborted", 4000);
		}

	}

	/**
	 * Password_ match_ check.
	 *
	 * @param password the password
	 * @param confirm_password the confirm_password
	 * @return true, if successful
	 */
	
	public boolean Password_Match_Check(String password,String confirm_password){
		if(!password.equals(confirm_password)){
			displayWithToast("Error-Password Mismatch",5000);
			return false;
		}
		return true;
	}

	/**
	 * Grey email.
	 *
	 * @param View v
	 */
	public void greyEmail(View V)
	{
		CheckBox emailCheck = ((CheckBox)findViewById(R.id.emailCheckbox));
		if(!emailCheck.isChecked())
			((EditText)findViewById(R.id.emailBox)).setEnabled(true);
		else
			((EditText)findViewById(R.id.emailBox)).setEnabled(false);					
	}

	/**
	 * Display user profile.
	 *
	 * @param View v
	 * @param user_uid the user_uid
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void displayUserProfile(View V, int user_uid) throws IOException{

		char [] user_info;
		String user_info_string;
		String the_user_name;
		String the_user_sex;

		user_info=myComm.sendData(("get=user&uid="+user_uid+"\n").getBytes());
		user_info_string=String.valueOf(user_info);

		User this_user = new User(user_info_string);


		the_user_name=this_user.getTheUserName();
		the_user_sex=this_user.getSex();
		
		//get the username and sex
		TextView username=((TextView)findViewById(R.id.username));
		TextView usersex=((TextView)findViewById(R.id.usersex));

		username.setText(the_user_name);
		usersex.setText(the_user_sex);
	}

	/**
	 * Display friend view.
	 *
	 * @param View v
	 * @param user_uid the user_uid
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	//show the friend View this has more information because the users are friends
	
	public void displayFriendView(View V, int user_uid) throws IOException{
		char [] user_info;
		String user_info_string;
		String the_user_name;
		String the_user_sex;
		String the_user_email;
		String the_user_status;
		String the_user_latitude;
		String the_user_longitude;

		user_info=myComm.sendData(("get=user&uid="+user_uid+"\n").getBytes());
		user_info_string=String.valueOf(user_info);

		//the User class parses the necessary information
		User this_user = new User(user_info_string);


		the_user_name=this_user.getTheUserName();
		the_user_sex=this_user.getSex();
		the_user_email=this_user.getEmail();
		the_user_status=this_user.getStatus();
		the_user_latitude=this_user.getLatitude();
		the_user_longitude=this_user.getLongitude();

		TextView username=((TextView)findViewById(R.id.username));
		TextView usersex=((TextView)findViewById(R.id.usersex));
		TextView useremail=((TextView)findViewById(R.id.useremail));
		TextView userstatus=((TextView)findViewById(R.id.userstatus));
		TextView userlatitude=((TextView)findViewById(R.id.userlatitude));
		TextView userlongitude=((TextView)findViewById(R.id.userlongitude));

		//set the values for the appropriate fields
		username.setText(the_user_name);
		usersex.setText(the_user_sex);
		useremail.setText(the_user_email);
		userstatus.setText(the_user_status);
		userlatitude.setText(the_user_latitude);
		userlongitude.setText("  "+the_user_longitude);
	}

	public void displayEventView() throws IOException {
		char [] event_info;
		String event_info_string;
		String event_name;
		String event_description;
		String event_date;
		String event_time;
		String event_longitude;
		String event_latitude;
		ArrayList<FormattedDisplay> attendees;
		
		event_info=myComm.sendData(("get=event&eid="+event_id+"\n").getBytes());
		
		event_info_string=String.valueOf(event_info);
		
		Event this_event=new Event(event_info_string);
		
		event_name=this_event.getname();
		event_description=this_event.getdescription();
		event_date=this_event.getdate();
		event_time=this_event.gettime();
		event_latitude=this_event.getlatitude();
		event_longitude=this_event.getlongitude();
		
		
		TextView eventname=((TextView)findViewById(R.id.eventname));
		TextView eventdate=((TextView)findViewById(R.id.eventdate));
		TextView eventtime=((TextView)findViewById(R.id.eventtime));
		TextView eventdescription=((TextView)findViewById(R.id.eventdescription));
	//	TextView eventlatitude=((TextView)findViewById(R.id.eventlatitude));
	//	TextView eventlongitude=((TextView)findViewById(R.id.eventlongitude));
		
		eventname.setText(event_name);
		eventdate.setText(event_date);
		eventtime.setText(event_time);
		eventdescription.setText(event_description);
		//eventlatitude.setText(event_latitude);
		//eventlongitude.setText(event_longitude);
		
		attendees=displayAttendees();
		populateList(attendees);
		/*
		for (int i=0; i<attendees.length; i++){
			displayWithToast(attendees[i],4000);
		}
		
		setListAdapter(new ArrayAdapter<String>(this, R.id.attendeelist, attendees));
		*/
	}
	public double calculateDistance(double latitude, double longitude)
	{
		return Math.sqrt(Math.pow(latitude-myLocation.getLatitude(),2)+Math.pow(longitude-myLocation.getLongitude(),2));
	}
	public ArrayList<FormattedDisplay> displayAttendees() throws IOException{
		char [] test;
		String event_info_string;
		String [] parse_users;
		
		ArrayList<FormattedDisplay> list_of_users=new ArrayList<FormattedDisplay>();
		
		
		test=myComm.sendData(("get=user&eventList.eid="+event_id+ "&uid="+uid+ "\n").getBytes());
		
		event_info_string=String.valueOf(test);
		parse_users=event_info_string.split("`");
	
		
		for(int i=0; i<parse_users.length-1; i++){
			User this_user=new User(parse_users[i]);
			list_of_users.add(this_user);
		}
//		String [] list_of_attendees= new String[list_of_users.size()];
//		for(int i=0; i<list_of_users.size(); i++){
//			
//			String name;
//			name=list_of_users.get(i).getTheUserName();
//			list_of_attendees[i]=name;
//		}
//		
		
		
//		return list_of_attendees;
		return list_of_users;
		
		
	}
	public boolean didUserJoinEventAlready() throws IOException
	{
		char[] result=null;
		String is_user_in_event;
		result = myComm.sendData(("get=eventList&uid="+uid+"&eid="+event_id+"\n").getBytes());
		is_user_in_event=String.valueOf(result);
	
		
		if ( Character.isDigit(is_user_in_event.charAt(0)) ){
			
			return true;
		}
		else{
			
			return false;
		}
		
	}


	/**
	 * Adds the event.
	 *
	 * @param eid the eid
	 */
	public void AddEvent(View V) throws IOException{
		
		char [] result;
		
		result = myComm.sendData(("add=eventList&uid="+uid+"&eid="+event_id+"\n").getBytes());
		
		if (result[0]=='0')
			displayWithToast("Event already added.", 4000);
		else{
			displayWithToast("Added event to eventlist", 4000);
			setContentView(R.layout.loggedinview);
		}
		
	}
	/**
	 * Removes the event.
	 *
	 * @param eid the eid
	 * @throws IOException 
	 */
	public void removeEvent(View V) throws IOException
	{
		char[] result=null;
			
		try {
			result = myComm.sendData(("del=eventList&uid="+uid+"&eid="+event_id+"\n").getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (result[0]!='0'){
			displayWithToast("Event deleted.", 4000);
			setContentView(R.layout.loggedinview);
		}
		//displayEventView();
	}
	/**
	 * Adds the friend.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void AddFriend(View V) throws IOException{
		
		addFriend(friend_uid);
		setContentView(R.layout.friendview);
		displayFriendView(V,friend_uid);
	}
	/**
	 * Adds the friend.
	 *
	 * @param uid the uid
	 */
	private void addFriend(int uid)
	{
		char[] result=null;
		try {
			result = myComm.sendData(("add=friend&uid1="+this.uid+"&uid2="+uid+"\n").getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (result[0]=='0')
			displayWithToast("User already added.", 4000);
		else
			displayWithToast("User event to friends list", 4000);
	}
	/**
	 * Removes the friend.
	 *
	 * @param View v
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public void RemoveFriend(View V) throws IOException{
		removeFriend(friend_uid);
		setContentView(R.layout.userprofile);		
		displayUserProfile(V,friend_uid);
	}


	/**
	 * Removes the friend.
	 *
	 * @param friendUid the friend uid
	 */
	private void removeFriend(int friendUid)
	{
		char[] result=null;
		try {
			result = myComm.sendData(("del=friend&uid1="+this.uid+"&uid2=" + friendUid +"\n").getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (result[0]=='0')
			displayWithToast("Friend already deleted", 4000);
		else
			displayWithToast("Friend deleted", 4000);
	}
	//the Restart,onResume,Pause, and Stop functions deals with loopback with Android emulator
	//loopback for Anroid emulator is 10.0.2.2 (not 127.0.0.1!)

	
	protected void onRestart()
	{
		super.onRestart();

		try {
			myComm = new SocketsClient("10.0.2.2");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	protected void onResume()
	{
		myProvider.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this);
		super.onResume();
		try {
			myComm = new SocketsClient("10.0.2.2");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	protected void onPause()
	{
		myProvider.removeUpdates(this);
		super.onPause();

	}

	
	protected void onStop()
	{
		super.onStop();
		try {
			myComm.closeConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	//function handles the logic behind selecting an event from the list
	public void onListItemClick(ListView parent, View v, int position,long id) {  
		FormattedDisplay disp = (FormattedDisplay)parent.getItemAtPosition(position);

		friend_uid=disp.userID();
		//user not event
		if(disp.userID()!=-1) {
			try {
				is_friend=isUserFriend(disp.userID());

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// if they are frinds, display the friend View UI 
			if(is_friend==true){
				setContentView(R.layout.friendview);
				try {
					displayFriendView(v,disp.userID());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			//otherwise show the normal user profile
			else{
				setContentView(R.layout.userprofile);
				try {
					displayUserProfile(v,disp.userID());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		else
		{
			//otherwise it must be an event (events do not have userIDs )
			
			event_id=disp.eventID();
			try {
				displayAttendees();
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			/*
			try {
				test=myComm.sendData(("get=user&eventList.eid="+event_id+ "&uid="+uid).getBytes());
				fireLongToast(String.valueOf(test),4000);
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			*/
			boolean didjoinevent=true;
			try {
				didjoinevent = didUserJoinEventAlready();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			//adds events to a particular user's list of events
			if (didjoinevent==true){
			try {
				
				setContentView(R.layout.joinedevent);
				displayEventView();
				
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//notifies user if adding event twice
			}
			else{
				try {
					
					setContentView(R.layout.event);
					displayEventView();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}

	}



	/**
	 * Gets the nearby events.
	 *
	 * @param View v
	 * @return the nearby events
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	private void getNearbyEvents(View v) throws IOException
	{
		StringBuilder toSend = new StringBuilder("get=event&location=");
		double latitude;
		double longitude;
		//update location if not null
		if(myLocation==null)
		{
			latitude = 0;
			longitude = 0;
		}
		else
		{
			latitude = myLocation.getLatitude();
			longitude = myLocation.getLongitude();
		}
		//add the # to serve as a delimeter when sending data to server
		toSend.append(latitude);
		toSend.append("#");
		toSend.append(longitude);
		toSend.append("#");
		toSend.append(radius);
		toSend.append("\n");
		char[] listOfEvents = myComm.sendData(toSend.toString().getBytes());
		displayEvents(listOfEvents);
	}



	/**
	 * Populate list.
	 *
	 * @param toDisplay the to display
	 */
	//populates the ArrayList that holds the data for our events and users. Data is further organized with FormattedDisplay class
	private void populateList(ArrayList<FormattedDisplay> toDisplay)
	{
		CustomAdapter myListDrawer = new CustomAdapter(this, R.layout.list, R.id.title, toDisplay);
		setListAdapter(myListDrawer);
		getListView().setTextFilterEnabled(true);
	}

	/**
	 * The Class CustomAdapter.
	 */
	//used to create the list view of our events and users
	private class CustomAdapter extends ArrayAdapter<FormattedDisplay> {

		/**
		 * Instantiates a new custom adapter.
		 *
		 * @param context the context
		 * @param resource the resource
		 * @param textViewResourceId the text view resource id
		 * @param objects the objects
		 */
		public CustomAdapter(Context context, int resource,
				int textViewResourceId, List<FormattedDisplay> objects) {               
			super(context, resource, textViewResourceId, objects);
		}

		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {   
			ViewHolder holder = null;
			TextView title = null;
			TextView detail = null;
			ImageView i11=null;
			//calls Formatted Display constructor. The getItem pulls the data from the corresponding place
			//on the list. The user selects this value onClick
			
			FormattedDisplay myFormattedDisplayObject= getItem(position);
			String[] displayStrings = myFormattedDisplayObject.displayStrings();
			if(null == convertView){
				convertView = mInflater.inflate(R.layout.list, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}
			//sets the title, image, and detail information for object in list
			holder = (ViewHolder) convertView.getTag();
			title = holder.gettitle();
			title.setText(displayStrings[0]);
			detail = holder.getdetail();
			detail.setText(displayStrings[1]);                                                     
			i11=holder.getImage();
			i11.setImageResource(R.drawable.icon);
			return convertView;
		}

		/**
		 * The Class ViewHolder.
		 */
		private class ViewHolder {

			/** The m row. */
			private View mRow;

			/** The title. */
			private TextView title = null;

			/** The detail. */
			private TextView detail = null;

			/** The i11. */
			private ImageView i11=null; 

			/**
			 * Instantiates a new view holder.
			 *
			 * @param row the row
			 */
			public ViewHolder(View row) {
				mRow = row;
			}

			/**
			 * Gets the title.
			 *
			 * @return the title
			 */
			public TextView gettitle() {
				if(null == title){
					title = (TextView) mRow.findViewById(R.id.title);
				}
				return title;
			}     

			/**
			 * Gets the detail.
			 *
			 * @return the detail
			 */
			public TextView getdetail() {
				if(null == detail){
					detail = (TextView) mRow.findViewById(R.id.detail);
				}
				return detail;
			}

			/**
			 * Gets the image.
			 *
			 * @return the image
			 */
			public ImageView getImage() {
				if(null == i11){
					i11 = (ImageView) mRow.findViewById(R.id.img);
				}
				return i11;
			}
		}
	}

	//updates user GPS coordinates
	public void onLocationChanged(Location location)
	{
		// TODO Auto-generated method stub
		this.myLocation = location;
		try {
			myComm.sendNonblocking(("loc&"+location.getLatitude()+"&"+location.getLongitude()+"&"+this.uid+"\n").getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	//notifies user GPS disables
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		displayWithToast("The system GPS service has been disabled.", 5000);
	}

	//notifies user GPS enabled
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		displayWithToast("GPS is now avaliable", 4000);

	}

	//notifies user of any change in the status of the GPS
	public void onStatusChanged(String location_provider, int status, Bundle otherVariables) {
		// TODO Auto-generated method stub
		switch (status)
		{
		case LocationProvider.OUT_OF_SERVICE:
			displayWithToast("The GPS is out of service.", 5000);
		case LocationProvider.TEMPORARILY_UNAVAILABLE:
			displayWithToast("The GPS is temporarially unavaliable", 5000);
		case LocationProvider.AVAILABLE:
			displayWithToast("GPS is now avaliable", 5000);
		}

	}
	 public void fireLongToast(String toShow, int duration) {
		 
		    int count=0;
			final Toast temp = Toast.makeText(this, toShow, duration);
			temp.setGravity(Gravity.CENTER, 0, 0);
		 
		         Thread t = new Thread() {
		 
		             public void run() {
		 
		                 int count = 0;
		 
		                 try {
		 
		                     while (count < 10) {
		 
		                         temp.show();
		 
		                         sleep(1850);
		 
		                         count++;
		 
		  
		 
		                         // DO SOME LOGIC THAT BREAKS OUT OF THE WHILE LOOP
		 
		                     }
		 
		                 } catch (Exception e) {
		 
		                     e.printStackTrace();
		 
		                 }
		 
		             }
		 
		         };
		         t.start();
	 }

}
